package com.zsy.springframework.beans.facotry.support;

import cn.hutool.core.util.StrUtil;
import com.zsy.springframework.beans.facotry.config.BeanDefinition;
import com.zsy.springframework.beans.facotry.exception.BeansException;
import com.zsy.springframework.beans.facotry.jiekou.one.DisposableBean;

import java.lang.reflect.Method;

public class DisposableBeanAdapter implements DisposableBean {
    private final Object bean;
    private final String beanName;
    private final String destoryMethodName;

    public DisposableBeanAdapter(Object bean, String beanName, BeanDefinition beanDefinition) {
        this.bean = bean;
        this.beanName = beanName;
        this.destoryMethodName = beanDefinition.getDestroyMethodName();
    }

    @Override
    public void destroy() throws Exception {
        if (bean instanceof DisposableBean) {
            ((DisposableBean) bean).destroy();
        }
        //注解配置destory-mothod 防止二次执行销毁方法
        if (StrUtil.isNotEmpty(destoryMethodName) && !(bean instanceof DisposableBean && "destory".equals(this.destoryMethodName))) {
            Method method = bean.getClass().getMethod(destoryMethodName);
            if (method == null) {
                throw new BeansException("Couldn't find a destroy method named '" + method + "' on bean with name '" + beanName + "'");
            }
            method.invoke(bean);
        }
    }
}
